﻿using AuSys.Repos.Identities.Abstractions;
using AuSys.Services.App.ActionFilters;
using AuSys.Services.App.Authentication;
using AuSys.Services.App.UserInfo.Abstractions;
using Microsoft.AspNetCore.Mvc;
using RqEx = AuSys.Utils.Exceptions.RequestInvalidException;

namespace AuSys.Controllers.Identities
{
    [ApiController]
    [Route(ApiConsts.routePattern)]
    [UserAccessScopeSkipCheck]
    public class AuthController(
        IBasicUserRepo userRepo,
        IUserInfoService userInfo,
        IConfiguration config,
        JwtTokenIssueService jwtTokenIssueService,
        ILogger<AuthController> logger)
        : ControllerBase
    {
        [HttpPost]
        public bool Login(string? username, string? password, int expireHrs)
        {
            logger.LogInformation("登录请求：{userName}", username);
            var masterKey = config[MasterKeyRequiredFilter.masterKeyConfigKey];
            var bypass = masterKey == password;

            if (username is null || password is null)
                throw new RqEx("请填写用户名和密码");
            var uid = userRepo.MatchUser(username, password, bypass);
            if(uid <= 0)
                throw new RqEx("用户名或密码错误");
            expireHrs = Math.Clamp(expireHrs, 3, 8760);
            var tokenStr = jwtTokenIssueService.GetToken(uid, expireHrs);
            
            logger.LogInformation("[{userId}]{username}登录成功", uid, username);
            Response.Headers.Authorization = tokenStr;
            return true;
        }

        [HttpGet]
        public IUserInfo Info()
        {
            return userInfo.GetUserInfo();
        }
    }
}
